package com.bestv.search.management.command;

import com.bestv.search.common.dataSource.DataSourceKey;
import com.bestv.search.common.model.SearchFieldInfo;
import com.bestv.search.common.model.SysUser;
import com.bestv.search.common.model.uid.UID;
import com.bestv.search.common.service.SearchConfigManager;
import com.bestv.search.common.util.DateUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.List;
import java.util.Map;

public class SearchConfigCommand {

    protected final Log log = LogFactory.getLog(getClass());
    private SearchConfigManager searchConfigManager;

    public SearchConfigManager getSearchConfigManager() {
        return searchConfigManager;
    }

    public void setSearchConfigManager(SearchConfigManager searchConfigManager) {
        this.searchConfigManager = searchConfigManager;
    }

    public String delete(SysUser user, Map<String, String[]> map, DataSourceKey dsKey) {
        String[] id = map.get("id");
        if ("".equals(id[0]))
            return "[error]";

        searchConfigManager.deleteSearchFieldInfo(dsKey, new Long(id[0]));
        return "{'result':'success','message':''}";
    }

    public String findForCombo(SysUser user, Map<String, String[]> map, DataSourceKey dsKey) throws JSONException {
        List<SearchFieldInfo> list = searchConfigManager.getSearchFieldInfos(dsKey);

        JSONArray array = new JSONArray();
        for (SearchFieldInfo ks : list) {
            JSONObject jo = new JSONObject();
            jo.put("name", ks.getName());
            jo.put("description", ks.getDescription());
            array.put(jo);
        }
        return "{'searchFields':" + array.toString() + "}";
    }

    public String find(SysUser user, Map<String, String[]> map, DataSourceKey dsKey) throws JSONException {
        String[] start = map.get("start");
        String[] limit = map.get("limit");

        int stat = 0, lmt = 20;
        if ("".equals(start[0]))
            stat = -1;
        else
            stat = Integer.parseInt(start[0]);
        if ("".equals(limit))
            lmt = -1;
        else
            lmt = Integer.parseInt(limit[0]);

        int count = searchConfigManager.getSearchFieldInfosCount(dsKey);
        List<SearchFieldInfo> list = searchConfigManager.getSearchFieldInfos(dsKey, stat, lmt);

        JSONArray array = new JSONArray();
        for (SearchFieldInfo ks : list) {
            JSONObject jo = new JSONObject();
            jo.put("id", String.valueOf(ks.getId()));
            jo.put("name", ks.getName());
            jo.put("description", ks.getDescription());
            jo.put("boost", String.valueOf(ks.getBoost()));
            jo.put("creator", ks.getCreator() == null ? "" : ks.getCreator().getUsername());
            jo.put("updateTime", DateUtil.convertDateToString("yyyy-MM-dd HH:mm:ss", ks.getUpdateTime()));
            array.put(jo);
        }
        return "{'totalCount':" + count + ",'scs':" + array.toString() + "}";
    }

    public String save(SysUser user, Map<String, String[]> map, DataSourceKey dsKey) {
        String[] id = map.get("id");
        String[] name = map.get("nm");
        String[] description = map.get("dp");
        String[] boost = map.get("wt");

        if ("".equals(name[0]))
            return "{'result':'failure','message':'fieldNull'}";
        if ("".equals(description[0]))
            return "{'result':'failure','message':'fieldNull'}";
        if ("".equals(boost[0]))
            return "{'result':'failure','message':'fieldNull'}";
        SearchFieldInfo existedSfi = null;

        existedSfi = searchConfigManager.getSearchInfoByName(dsKey, name[0]);
        if (existedSfi != null) {
            if (!"".equals(id[0])) {
                if (existedSfi.getId() != new Long(id[0]))
                    return "[existed]";
            } else
                return "[existed]";
        }
        SearchFieldInfo sfi = null;
        if ("".equals(id[0])) {
            sfi = new SearchFieldInfo();
            sfi.setId(new Long(UID.getUID(sfi)));
        } else {
            sfi = existedSfi == null ? searchConfigManager.getById(dsKey, new Long(id[0])) : existedSfi;
        }
        sfi.setName(name[0]);
        sfi.setDescription(description[0]);
        float bt = Float.parseFloat(boost[0]);
        bt = Math.round(bt * 100) / 100f;
        sfi.setBoost(bt);
        sfi.setCreator(user);
        sfi.setUpdateTime(new Date());
        searchConfigManager.saveSearchFieldInfo(dsKey, sfi);
        return "{'result':'success','message':''}";
    }

    public String get(SysUser user, Map<String, String[]> map, DataSourceKey dsKey) {
        String result = "";
        String[] id = map.get("id");

        if (id == null || "".equals(id[0]))
            return "[error]";
        SearchFieldInfo sfi = searchConfigManager.getById(dsKey, new Long(id[0]));

        try {
            JSONObject jo = sfiToJSONObject(sfi);
            result = jo.toString();
        } catch (JSONException e) {
            log.error(e);
        }
        return result;
    }

    private JSONObject sfiToJSONObject(SearchFieldInfo sfi) throws JSONException {
        JSONObject jo = new JSONObject();
        jo.put("nm", sfi.getName());
        jo.put("bt", String.valueOf(sfi.getBoost()));
        jo.put("dp", sfi.getDescription());
        return jo;
    }
}
